package com.nbsaas.boot.script.ext.resource;

import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.script.api.apis.ScriptTemplateApi;
import com.nbsaas.boot.script.api.domain.request.ScriptTemplateRequest;
import com.nbsaas.boot.script.api.domain.response.ScriptTemplateResponse;
import com.nbsaas.boot.script.ext.apis.ScriptResource;
import com.nbsaas.boot.script.ext.domain.simple.ScriptSource;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

@Component
public class SpringScriptSource implements ScriptResource {

    @Resource
    private ScriptTemplateApi scriptTemplateApi;

    @Override
    public String getPrefix() {
        return "model:";
    }

    @Override
    public ScriptSource loadScript(String path) {

        ScriptTemplateRequest req=new ScriptTemplateRequest();
        String id=path.substring(getPrefix().length());
        req.setId(id);
        ResponseObject<ScriptTemplateResponse> res = scriptTemplateApi.view(req);
        if (res.getCode()!=200){
            return null;
        }
        ScriptTemplateResponse data = res.getData();

        ScriptSource result = new ScriptSource();
        result.setScript(data.getContent());
        if (data.getLastDate()!=null){
            result.setTimestamp(data.getLastDate().getTime());
        }
        return result;
    }
}
